{% extends  'common_project_tpl.html' %}
{% block css %}
    <style>
        .flex-show {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .pre {
            margin: 10px;
            background-color: #4a4a4a;
            color: #f5f5f5;
            white-space: pre-wrap;
            word-wrap: break-word;
            max-height: 500px;
        }

        .grid_show {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 0px 10px;
            margin: 10px;
        }
    </style>
{% endblock %}
{% block content %}
    <div class="container-fluid" style="margin-top: 20px;">
        {% for job, value in job_list.items %}
            {% if "server" in job %}
                <div class="panel panel-primary">
            {% else %}
                <div class="panel panel-info">
            {% endif %}
                    <div class="panel-heading flex-show" id="{{ job }}_heading">
                        <div style="text-align: center">
                            <h3 class="panel-title">{{ job }}</h3>
                        </div>
                        <div>上次构建：{{ value.build_time }}</div>
                        <div>构建编号：{{ value.last_build_name }}</div>
                        <div>状态：{{ value.build_status }}</div>
                        <div>
                            {% if value.allure_report %}
                                <a target="_blank" href="{{ value.allure_report }}" class="btn btn-warning btn-sm">Allure报告</a>
                            {% endif %}
                            <button class="btn btn-success btn-sm build">立即构建</button>
                            <button class="btn btn-info btn-sm console">console</button>
                        </div>
                    </div>
                    {% if value.params %}
                        <div class="label-warning label" style="margin: 5px;">此构建需要参数：</div>
                        <form id="{{ job }}_form" class="grid_show">
                        {% for param in value.params %}
                            <div class="form-group">
                                <label for="{{ job }}{{ param.name }}">{{ param.description }}</label>
                                {% if param.type == "StringParameterDefinition" %}
                                    <input type="text" class="form-control" id="{{ job }}{{ param.name }}"
                                           name="{{ param.name }}" value="{{ param.default }}">
                                {% else %}
                                    <select class="form-control" name="{{ param.name }}" id="{{ job }}{{ param.name }}">
                                        {% for choice in param.choices %}
                                            {% if choice == param.default %}
                                                <option value="{{ choice }}" selected>{{ choice }}</option>
                                            {% else %}
                                                <option value="{{ choice }}">{{ choice }}</option>
                                            {% endif %}
                                        {% endfor %}
                                    </select>
                                {% endif %}
                            </div>
                        {% endfor %}

                    </form>
                    {% endif %}
                    <div class="panel-body hide pre pre-scrollable" id="{{ job }}">
                    </div>
                </div>
        {% endfor %}
    </div>
    {% csrf_token %}
{% endblock %}
{% block js %}
    <script>
        $(function () {
            bindBuildBtn();
            bindConsoleBtn();
        })
        var socket = {}
        var page_id = $("[name='csrfmiddlewaretoken']").val()

        function bindBuildBtn() {
            $(".build").click(function () {
                let name = $(this).parent().parent().find("h3").text()
                initConsole(name);
                let form = $("#" + name + '_form')
                let params = {};
                if (form) {
                    $.each(form.serializeArray(), function (i, item) {
                        params[item.name] = item.value;
                    })
                }
                $.ajax({
                    url: "{% url 'main:api_cases' pro_id %}",
                    data: JSON.stringify({
                        project:{{ pro_id }},
                        case_name: name,
                        params: params
                    }),
                    dataType: 'json',
                    type: 'post',
                    contentType: 'application/json',
                    headers: {
                        'X-CSRFTOKEN': $("[name='csrfmiddlewaretoken']").val()
                    },
                    success: function (res) {
                        console.log(res)
                        if (res.ret === 0) {
                            alert(name + '已经开始执行构建，请等待构建对象生成后请查看console信息！');
                            getBuildConsole(name);
                        } else {
                            alert(res.msg);
                        }
                    }
                })
            })
        }

        function bindConsoleBtn() {
            $(".console").click(function () {
                let name = $(this).parent().parent().find("h3").text();
                let el = $("#" + name);
                if (el.hasClass("hide")) {
                    getBuildConsole(name);
                } else if (!socket[name + '-' + page_id]) {
                    el.addClass("hide");
                }
            })
        }

        function getBuildConsole(name) {
            if (!socket[name + '-' + page_id]) {
                initConsole(name);
                $.ajax({
                    url: "{% url 'main:api_cases' pro_id %}",
                    data: {
                        project:{{ pro_id }},
                        case_name: name
                    },
                    dataType: 'json',
                    type: 'get',
                    success: function (res) {
                        let el = $("#" + name);
                        if (res.ret === 0) {
                            el.text(res.msg);
                            el.removeClass('hide');
                        } else {
                            el.removeClass('hide');
                            webSocket(name);
                            noticeGenerator(name);
                        }
                    }
                })
            }
        }

        function initConsole(console_id) {
            let el = $('#' + console_id);
            el.text('');
            el.addClass("hide");
        }

        function webSocket(name) {
            if (!socket[name + '-' + page_id]) {
                let hostname = window.location.hostname;
                let port = window.location.port;
                if (port) {
                    port = ':' + port;
                }
                let url = `ws://${hostname}${port}/wscases/${name}/`;
                socket[name + '-' + page_id] = new WebSocket(url);
                console.log(socket)
            }
            socket[name + '-' + page_id].onopen = function () {
                socket[name + '-' + page_id].send(name);
            }
            socket[name + '-' + page_id].onclose = function () {
                socket[name + '-' + page_id] = null;
                console.log(socket);
                refreshJob(name);
            }
            socket[name + '-' + page_id].onmessage = function (event) {
                let el = $('#' + name);
                el.append(event.data);
            }
            window.onbeforeunload = function () {
                socket[name + '-' + page_id].close();
            }
        }

        function noticeGenerator(name) {
            $.ajax({
                url: "{% url 'main:api_cases' pro_id %}",
                data: {
                    project:{{ pro_id }},
                    case_name: name
                },
                dataType: 'json',
                type: 'put',
                headers: {
                    'X-CSRFTOKEN': $("[name='csrfmiddlewaretoken']").val()
                },
                success: function (res) {
                    console.log(res)
                }
            })
        }
        function refreshJob(name) {
            $.ajax({
                    url: "{% url 'main:api_cases' pro_id %}",
                    data: {
                        project:{{ pro_id }},
                        case_name: name,
                        refresh: true
                    },
                    dataType: 'json',
                    type: 'get',
                    success: function (res) {
                        let el = $("#" + name+"_heading");
                        $(el.find('div')[1]).text("上次构建："+ res.msg.build_time);
                        $(el.find('div')[2]).text("构建编号："+ res.msg.last_build_name);
                        $(el.find('div')[3]).text("构建编号："+ res.msg.build_status);
                        if (res.msg.allure_report){
                            $(el.find('a')).attr("href",res.msg.allure_report)
                        }
                    }
            })
        }

    </script>
{% endblock %}